/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Parser;

import Entities.Content;
import Entities.Mail;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author fabio
 */
public final class ContentParser {

    private Mail mail;
    private Content content;
    private MimeMessage mimeMessage;
    private ArrayList links;
    private int CapsLong = 0;
    private int CapsAvg = 0;
    private int CapsTotal = 0;
    private int ImgCounter = 0;
    private int WordCounter = 0;
    private int LineCounter = 1;
    private int CharactersSpacesHtml = 0;
    private int CharactersNoSpacesHtml = 0;
    private int CharactersSpacesNoHtml = 0;
    private int CharactersNoSpacesNoHtml = 0;

    ContentParser(Mail mail, MimeMessage mimeMessage) {
        this.mail = mail;
        this.mimeMessage = mimeMessage;
        this.content = new Content(mail);
        this.links = new ArrayList<URL>();
    }

    public void run() throws MessagingException, IOException {
        System.setProperty("mail.mime.decodetext.strict", "false");
        System.setProperty("mail.mime.address.strict", "false");
        System.setProperty("mail.mime.parameters.strict", "false");
        System.setProperty("mail.mime.base64.ignoreerrors", "true");
        System.setProperty("mail.mime.multipart.ignoreexistingboundaryparameter", "true");

        ArrayList<String> messagesList = new ArrayList<String>();
        Object objectM = mimeMessage.getContent();
        if (objectM instanceof String) {
            String messageS = (String) objectM;
            messagesList.add(messageS);
        } else if (objectM instanceof Multipart) {
            Multipart mpMessage = (Multipart) objectM;
            for (int i = 0; i < mpMessage.getCount(); i++) {
                BodyPart part = mpMessage.getBodyPart(i);
                if (part.getContent() instanceof String) {
                    String messageS = part.getContent().toString();
                    //System.out.println(messageS);
                    messagesList.add(messageS);
                }
            }
        }
        wordSpliter(messagesList);

        content.updateContent(CapsLong, CapsAvg, CapsTotal, ImgCounter, WordCounter, LineCounter, CharactersSpacesHtml, CharactersNoSpacesHtml, CharactersSpacesNoHtml, CharactersNoSpacesNoHtml, links);
        //System.out.println(content.toString());
    }

    public void wordSpliter(ArrayList<String> messagesList) {

        for (String s : messagesList) {
            links = MailTextParser.getLinks(s);
            //LinkCounter = links.size();
            String textNoHtmlSpaces = MailTextParser.removeHTML(s);
            String textNoHtmlNoLines = MailTextParser.removeLines(textNoHtmlSpaces);
            String textNoHtmlNoSpaces = MailTextParser.removeSpaces(textNoHtmlNoLines);
            String textNoSpacesHtml = MailTextParser.removeSpaces(MailTextParser.removeLines(s));
            String stringStats = textNoHtmlSpaces;
            stringStats(stringStats);
            // System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXX\n" + MailTextParser.escapeLineBreaksForHTML(s));
            CharactersSpacesHtml += s.length();
            CharactersSpacesNoHtml += textNoHtmlSpaces.length();
            CharactersNoSpacesNoHtml += textNoHtmlNoSpaces.length();
            CharactersNoSpacesHtml += textNoSpacesHtml.length();
            ImgCounter += MailTextParser.countImgs(s);
            s = textNoHtmlNoLines;
            String[] words = s.split("[\\W]");
            for (String word : words) {
                word = word.toLowerCase();
                //String alphaOnly = input.replaceAll("[^a-zA-Z]+", "");
                //String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+", "");
                word.replaceAll("[^a-zA-Z]", "");
                if (!word.isEmpty()) {
                    content.insertWord(word);
                    WordCounter++;
                }
            }
        }
        if (CharactersNoSpacesNoHtml == 0) {
            CapsAvg = 0;
        } else {
            CapsAvg = Math.round((float) CapsTotal / (float) CharactersNoSpacesNoHtml * 100);
        }
    }

    public void stringStats(String str) {
        boolean oldCaps = false;
        int capsLocal = 0;
        if (str == null || str.length() == 0) {
            LineCounter = 0;
        } else {
            int len = str.length();
            for (int pos = 0; pos < len; pos++) {
                char c = str.charAt(pos);
                //Verificar linhas
                if (c == '\r') {
                    LineCounter++;
                    if (pos + 1 < len && str.charAt(pos + 1) == '\n') {
                        pos++;
                    }
                } else if (c == '\n') {
                    LineCounter++;
                }
                //Verificar maiusculas
                if (Character.isLetter(c)) {
                    if (Character.isUpperCase(c)) {
                        CapsTotal++;
                        capsLocal++;
                        if (oldCaps == true) {
                            CapsLong++;
                        }
                        if (capsLocal > CapsLong) {
                            CapsLong = capsLocal;
                        }
                    } else {
                        oldCaps = false;
                        capsLocal = 0;
                    }
                } else {
                    oldCaps = false;
                }
                //@TODO paragrafos
            }
        }
    }

    Content getContent() {
        return content;
    }
}
